package com.atguigu.crowd.mvc.controller;

import com.atguigu.crowd.constant.CrowdConstant;
import com.atguigu.crowd.exception.AccessForbiddenException;
import com.atguigu.crowd.exception.LoginAcctAlreadyInUseException;
import com.atguigu.crowd.service.api.AdminService;
import com.atguigu.crowd.until.CrowdUtil;
import com.github.pagehelper.PageInfo;
import crowd.entity.Admin;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;

@Controller
public class AdminController {

    @Autowired
    private AdminService adminService;

    /**
     * 更新Admin数据
     * @param admin
     * @param pageNum
     * @param keyword
     * @return
     */
    @RequestMapping("/admin/update.html")
    public String update(Admin admin, @RequestParam("pageNum") Integer pageNum, @RequestParam("keyword") String keyword){

        adminService.updateAdmin(admin);

        return "redirect:/admin/get/page.html?pageNum=" + pageNum + "&keyword=" + keyword;

    }

    /**
     * 回显用户数据至更新页面
     * @param adminId
     * @param modelMap
     * @return
     */
    @RequestMapping("admin/to/edit/page.html")
    public String toEditPage(@RequestParam("adminId") Integer adminId,
                              ModelMap modelMap){
        // 根据adminId查询该用户数据
        Admin admin = adminService.getAdminById(adminId);

        // 将admin对象放入modelMap中
        modelMap.addAttribute("admin", admin);

        return "admin-edit";

    }


    /**
     * 添加Admin用户功能
     * @param admin
     * @return
     */
    @PreAuthorize("hasAuthority('user:save')")
    @RequestMapping("/admin/save.html")
    public String saveAdmin(Admin admin){

        try {
            adminService.saveAdmin(admin);
        } catch (Exception e) {
            // 如果违反账号唯一性原则，则抛出此自定义异常
            if (e instanceof DuplicateKeyException){
                throw new LoginAcctAlreadyInUseException(CrowdConstant.MESSAGE_LOGIN_ALREADY_IN_USE);
            }
        }

        //重定向至用户列表的最后一页
        return "redirect:/admin/get/page.html?pageNum=" + Integer.MAX_VALUE;

    }

    /**
     * 删除用户功能
     * @param adminId
     * @param pageNum
     * @param keyword
     * @return
     */
    @RequestMapping("/admin/remove/{adminId}/{pageNum}/{keyword}.html")
    public String removeAdmin(@PathVariable("adminId") Integer adminId,
                              @PathVariable("pageNum") Integer pageNum,
                              @PathVariable("keyword") String keyword){

        // 根据adminId删除用户
        adminService.removeAdmin(adminId);

        // 避免刷新页面时重复提交删除请求，直接重定向
        return "redirect:/admin/get/page.html?pageNum=" + pageNum + "&keyword=" + keyword;

    }

    /**
     * 用户维护的分页功能
     * @param keyword
     * @param pageNum
     * @param pageSize
     * @param modelMap
     * @return
     */
    @RequestMapping("/admin/get/page.html")
    public String getAdminPage(@RequestParam(value = "keyword", defaultValue = "") String keyword,// 浏览器不提供关键词时，默认值为空
                               // 未提供pageNum时，默认跳至第一页
                               @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                               // 默认只显示5条信息
                               @RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize,
                               // 将分页信息放置modelMap中
                               ModelMap modelMap){

        // 查询得到分页数据
        PageInfo<Admin> pageInfo = adminService.getPageInfo(keyword, pageNum, pageSize);

        // 将分页数据放入modelMap中
        ModelMap modelMap1 = modelMap.addAttribute(CrowdConstant.ATTR_NAME_PAGE_INFO, pageInfo);

        return "admin-page";

    }


    /**
     * 退出登录
     * @param session
     * @return
     */
    @RequestMapping("/admin/do/logout.html")
    public String doLogout(HttpSession session){
        // 强制session失效
        session.invalidate();

        return "redirect:/admin/to/login/page.html";
    }



    /**
     * 登录至主页
     * @param loginAcct
     * @param userPswd
     * @param httpSession
     * @return 重定向至主页
     */
    @RequestMapping("/admin/do/login.html")
    public String doLogin(@RequestParam("loginAcct") String loginAcct,
                          @RequestParam("userPswd") String userPswd, HttpSession httpSession){

        // 调用adminService执行登录检查
        // 如果登录正常则继续往下，失败则抛出异常
        Admin admin = adminService.getAdminByLoginAcct(loginAcct, userPswd);

        // 将成功登录的对象放入session域中
        httpSession.setAttribute(CrowdConstant.ATTR_NAME_LOGIN_ADMIN, admin);

        // 防止重复提交表单，重定向至主页
        return "redirect:/admin/to/main/page.html";

    }

}
